import {
	addUseCard,
	getAllUnitList,
	checkUserCard
} from "@/views/authorization-management/use-card/api/use-card.js";
import dbl from "@/utils/dbl";
import propertyList from "~/views/authorization-management/use-card/add/property-list.vue";
import { getDict } from "~/utils";
import uploadMedia from "~/components/upload-media.vue";

export default {
	components: {
		propertyList: propertyList,
		uploadMedia
	},
	data() {
		return {
			modelType: "use-card",
			myHeader: { Authorization: dbl.get("token") },
			//弹出框 初始时隐藏
			dialogVisible: false,
			formObj: {
				useCard: {
					useCardId: "",
					authorizationNumber: "",
					apUiId: "",
					unitName: "",
					authorizationType: "",
					authorizationTime: "",
					remarks: ""
				},
				//附件
				fileList: [],
				useCardPropertyList: [],
				propertyIdList: []
			},
			//使用状态
			useStatusCode: [],
			//授权类型
			authTypeLists: [],
			//授权用途集合
			authorizationUseList: [],
			//实际用途
			practicalUseList: [],
			unitList: [],
			rules: {
				useCard: {
					apUiId: [
						{
							required: true,
							message: "请选择使用单位",
							trigger: "blur"
						}
					],
					authorizationType: [
						{
							required: true,
							message: "请选择授权类型",
							trigger: "blur"
						}
					],
					authorizationTime: [
						{
							required: true,
							message: "请选择时间",
							trigger: "blur"
						}
					]
				}
			},
			//筛选过滤列表
			filterItemList: [
				{
					label: "单选筛选",
					inputType: "radio",
					name: "radio",
					showAll: false,
					children: [
						{ label: "不限", value: "0" },
						{ label: "未授权", value: "1" }
					]
				}
			]
		};
	},

	//载入事件
	mounted: function() {
		let date = new Date();
		let year = date.getFullYear(); // 年
		let month = date.getMonth() + 1; // 月
		let day = date.getDate(); // 日
		this.formObj.useCard.authorizationTime = year + "-" + month + "-" + day;
		//使用证随机码
		// this.formObj.useCard.authorizationNumber = this.randomWord(
		//     false,
		//     10,
		//     10
		// );
		//获取使用单位的下拉狂列表
		this.getUnit();
	},
	created() {
		this.useStatusCode = getDict("use-status");
		this.authTypeLists = getDict("authorization-type");
		this.authorizationUseList = getDict("authorization-use");
		this.practicalUseList = getDict("practical-use");

		//把实际用途的码值转成数字
		if (null != this.practicalUseList && this.practicalUseList.length > 0) {
			for (let i = 0; i < this.practicalUseList.length; i++) {
				this.practicalUseList[i].value = parseInt(
					this.practicalUseList[i].value
				);
			}
		}
		//把授权用途的码值转成数字
		if (
			null != this.authorizationUseList &&
			this.authorizationUseList.length > 0
		) {
			for (let i = 0; i < this.authorizationUseList.length; i++) {
				this.authorizationUseList[i].value = parseInt(
					this.authorizationUseList[i].value
				);
			}
		}
	},
	computed: {
		defaultParams() {
			return {
				keyword: null,
				radio: 0
			};
		},
		chooseDialogAttrs() {
			return {
				title: "授权物业信息",
				placeholder: "请输入合同编号",
				url: `/api/usecard/property/list`,
				width: "1200px",
				searchKey: "keyword",
				showIndex: true,
				showData: [
					{
						prop: "propertyId",
						label: "物业编号",
						width: "200",
						align: "center"
					},
					{
						prop: "propertyName",
						label: "物业名称",
						width: "140",
						align: "center"
					},
					{
						prop: "propertyRightStr",
						label: "物业产权",
						width: "200",
						align: "center"
					},
					{
						prop: "propertyAddress",
						label: "物业地址",
						width: "200",
						align: "center"
					},
					{
						prop: "authorizationStatus",
						label: "授权状态",
						width: "200",
						align: "center",
						formatter: this.dataFormatter
					}
				]
			};
		}
	},
	methods: {
		// 监听弹窗选中
		handleChoose(data) {
			this.formObj.useCardPropertyList = data;
			// this.form = { ...this.form, ...data };
		},
		/**
		 * 弹出物业信息列表
		 */
		showPropertyListInfo: function() {
			this.$refs.propertyList.show();
		},

		/**
		 * 获取使用单位的下拉狂列表
		 */
		getUnit() {
			getAllUnitList()
				.then(resp => {
					let obj = resp.data.data;
					this.unitList = obj;
				})
				.catch(error => {
					this.$message({
						type: "error",
						message: "使用单位获取失败"
					});
				})
				.finally(() => (this.loading = false));
		},

		// 上传成功
		sendData() {
			this.$refs.ruleForm.validate(async valid => {
				if (valid) {
					if (null != this.formObj.useCardPropertyList) {
						let size = this.formObj.useCardPropertyList.length;
						for (let i = 0; i < size; i++) {
							if (
								null == this.formObj.useCardPropertyList[i].authorizationUse
							) {
								this.$alert("第" + (i + 1) + "行授权用途没有选择", "提示", {
									confirmButtonText: "确定"
								});
								return;
							}
							if (null == this.formObj.useCardPropertyList[i].practicalUse) {
								this.$alert("第" + (i + 1) + "行实际用途没有选择", "提示", {
									confirmButtonText: "确定"
								});
								return;
							}
							if (null == this.formObj.useCardPropertyList[i].startTime) {
								this.$alert("第" + (i + 1) + "行开始时间没有选择", "提示", {
									confirmButtonText: "确定"
								});
								return;
							}
							if (null == this.formObj.useCardPropertyList[i].endTime) {
								this.$alert("第" + (i + 1) + "行结束时间没有选择", "提示", {
									confirmButtonText: "确定"
								});
								return;
							}

							//结束时间不能小开开始时间
							if (
								Date.parse(this.formObj.useCardPropertyList[i].endTime) <
								Date.parse(this.formObj.useCardPropertyList[i].startTime)
							) {
								this.$alert(
									"第" + (i + 1) + "行结束时间不能小于开始时间",
									"提示",
									{
										confirmButtonText: "确定"
									}
								);
								return;
							}
						}
					}

					let checkval = { apUiId: "", propertyIdList: [] };
					checkval.apUiId = this.formObj.useCard.apUiId;

					if (this.formObj.useCardPropertyList.length > 0) {
						for (let i = 0; i < this.formObj.useCardPropertyList.length; i++) {
							checkval.propertyIdList.push(
								this.formObj.useCardPropertyList[i].propertyId
							);
						}
					}
					//校验重复记录
					checkUserCard(checkval)
						.then(resp => {
							let bol = resp.data.data.bol;
							let mes = resp.data.data.mes;

							if (bol == false) {
								this.$refs["ruleForm"].validate(valid => {
									if (valid) {
										console.log(this.formObj.useCard.apUiId);
										if (null != this.unitList && this.unitList.length > 0) {
											for (let i = 0; i < this.unitList.length; i++) {
												if (
													this.unitList[i].apUiId == this.formObj.useCard.apUiId
												) {
													this.formObj.useCard.unitName = this.unitList[
														i
													].unitName;
												}
											}
										}
										// 不管有没有上传附件，都会触发onSuccess的钩子，所以提交表单的事件不需要填两遍了
										this.$refs.useCardFile.submit(
											"apply-unit",
											this.formObj.useCard.useCardId
										);
									} else {
										return false;
									}
								});
							} else {
								this.$alert("已存在被绑定的物业编号：" + mes, "提示", {
									confirmButtonText: "确定"
								});
							}
						})
						.catch(error => {
							this.$message({
								type: "error",
								message: "操作失败"
							});
						})
						.finally(() => (this.loading = false));
				}
			});
		},
		/**
		 * 保存表单信息
		 * @returns {Promise<void>}
		 */
		saveEntity(response, file, fileList) {
			this.loading = true;
			this.formObj.useCard.useCardId = response.data;
			addUseCard(this.formObj).then(data => {
				this.$message({
					type: "success",
					message: "操作成功"
				});
				//操作完成 跳转页面
				this.loading = false;
				this.$router.push("/permission-manage/use-card-list");
			});
			//验证授权用途和实际用途是否选择
		},

		/**
		 * 列表复选框取值
		 */
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},

		/**
		 * 删除物业
		 */
		deleteProperty() {
			let multipleSize = this.multipleSelection.length;
			if (multipleSize > 0) {
				let listSize = this.formObj.useCardPropertyList.length;
				for (let i = 0; i < multipleSize; i++) {
					if (listSize > 0) {
						for (let k = 0; k < listSize; k++) {
							if (
								this.multipleSelection[i].propertyId ==
								this.formObj.useCardPropertyList[k].propertyId
							) {
								this.formObj.useCardPropertyList.splice(k, 1);
							}
						}
					}
				}
			} else {
				this.$alert("没有选择要删除的行", "提示", {
					confirmButtonText: "确定"
				});
				return;
			}
		},

		/**
		 * 重置
		 */
		resetForm() {
			this.$refs["ruleForm"].resetFields();
		},

		//返回
		goBack() {
			this.$router.push("/permission-manage/use-card-list");
		},

		/**
		 * 码值转换
		 * @param row
		 * @param column
		 * @param cellValue
		 * @returns {string|*}
		 */
		dictVal_useStatus: function(row, column, cellValue) {
			let obj = this.useStatusCode.find(p => p.value == cellValue);
			if (obj) {
				return obj.label;
			}
			return "";
		},

		/*
		 ** randomWord 产生任意长度随机字母数字组合
		 ** randomFlag 是否任意长度 min 任意长度最小位[固定位数] max 任意长度最大位
		 */
		randomWord(randomFlag, min, max) {
			let str = "",
				range = min,
				arr = [
					"A",
					"B",
					"C",
					"D",
					"E",
					"F",
					"G",
					"H",
					"I",
					"J",
					"K",
					"L",
					"M",
					"N",
					"O",
					"P",
					"Q",
					"R",
					"S",
					"T",
					"U",
					"V",
					"W",
					"X",
					"Y",
					"Z",
					"0",
					"1",
					"2",
					"3",
					"4",
					"5",
					"6",
					"7",
					"8",
					"9"
				];

			if (randomFlag) {
				range = Math.round(Math.random() * (max - min)) + min; // 任意长度
			}
			for (let i = 0; i < range; i++) {
				let pos = Math.round(Math.random() * (arr.length - 1));
				str += arr[pos];
			}
			return str;
		}
	}
};
